/**
 * Copyright 2012 Tautvydas Andrikys
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
package inet.app.vod.facebook;

import java.net.URLEncoder;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.webkit.WebView;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.inet.app.framework.util.Log;

/**
 * Like button for facebook
 */
public class LikeView extends WebView {

	private Facebook facebook = null;
	private String uri = "";
	private boolean initializing = false;
	private WebViewClient client = new WebViewClient();
	private Activity activity = null;

	public LikeView(Context context) {
		super(context.getApplicationContext());
		initialize(context);
	}

	public LikeView(Context context, AttributeSet attrs) {
		super(context.getApplicationContext(), attrs);
		initialize(context);
	}

	public LikeView(Context context, AttributeSet attrs, int defStyle) {
		super(context.getApplicationContext(), attrs, defStyle);
		initialize(context);
	}

	/**
	 * Set facebook application key
	 * 
	 * @param applicationKey
	 * 
	 * @return for method chaining
	 */
	public LikeView setApplicationKey(String applicationKey) {
		facebook = new Facebook(applicationKey);
		return this;
	}

	/**
	 * Set uri you want to like
	 * 
	 * @param uri
	 * 
	 * @return for method chaining
	 */
	public LikeView setUriToLike(String uri) {
		this.uri = uri;
		return this;
	}

	/**
	 * You must set like uri and application key for this method to work
	 */
	public void load() {
		if (facebook != null && uri.length() > 0) {
			SharedPreferences preferences = PreferenceManager
					.getDefaultSharedPreferences(activity);
			String access_token = preferences.getString("access_token", null);
			long expires = preferences.getLong("access_expires", 0);
			if (access_token != null) {
				facebook.setAccessToken(access_token);
			}
			if (expires != 0) {
				facebook.setAccessExpires(expires);
			}
			loadForLikeUrl();
		}
	}

	/**
	 * Initialize view
	 * 
	 * @param context
	 *            must be Activity
	 * @throws IllegalArgumentException
	 *             if context is not Activity
	 */
	private void initialize(Context context) throws IllegalArgumentException {
		if (context == null || !(context instanceof Activity)) {
			throw new IllegalArgumentException(
					"You must use Activity as FacebookLike context");
		}
		this.activity = (Activity) context;
		setBackgroundColor(0x00000000);
		getSettings().setJavaScriptEnabled(true);
		setFocusable(true);
		setFocusableInTouchMode(false);
		setWebViewClient(client);
	}

	/**
	 * Loads like button from facebook
	 */
	private void loadForLikeUrl() {
		String url = "http://www.facebook.com/plugins/like.php?api_key="
				+ facebook.getAppId()
				+ "&extended_social_context=false&font=arial&layout=button_count&locale=en_US"
				+ "&node_type=link&sdk=joey&send=false&show_faces=false&width=450&href="
				+ URLEncoder.encode(uri);
		Log.d("url_like_facebook= " + url);
		loadUrl(url);
	}

	@Override
	public void onWindowFocusChanged(boolean hasWindowFocus) {
		super.onWindowFocusChanged(hasWindowFocus);
		initializing = false;
	}

	/**
	 * Show facebook login from its sdk if user is not logged in
	 * 
	 * @param ev
	 * 
	 * @return
	 */
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if (initializing) {
			return false;
		}
		if (!facebook.isSessionValid()) {
			initializing = true;
			facebook.authorize(activity, new String[] {},
					Facebook.FORCE_DIALOG_AUTH, new Facebook.DialogListener() {

						public void onFacebookError(FacebookError e) {
							initializing = false;
						}

						public void onError(DialogError e) {
							initializing = false;
						}

						public void onCancel() {
							initializing = false;
						}

						public void onComplete(Bundle values) {
							SharedPreferences.Editor editor = PreferenceManager
									.getDefaultSharedPreferences(activity)
									.edit();
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();
							client.setClickAfterLoad(true);
							loadForLikeUrl();
							initializing = false;
						}
					});
			return false;
		}
		return super.onTouchEvent(ev);
	}

}
